#ifndef __TCPCONNECTION_H__
#define __TCPCONNECTION_H__

#include "Socket.hpp"
#include "SocketIO.hpp"
#include "InetAddress.hpp"
#include "Message.hpp"

#include <functional>
#include <memory>

using std::shared_ptr;
using std::function;

namespace cdm{

class EventLoop;

class TCPConnection;
using TCPConnectionPtr = shared_ptr<TCPConnection>;
using TCPCallbcak = function<void(TCPConnectionPtr)>;

//继承类，为了在成员函数内部通过this指针直接获取shared_ptr
class TCPConnection
:public std::enable_shared_from_this<TCPConnection>{

public:
    TCPConnection(int fd,EventLoop *);
    ~TCPConnection();
    string  recive();
    int     readPacket(Packet &);
    void    send(const string &);
    void    sendInLoop(const string &msg);
    void    sendInLoop(const TLV &data);

    void    shutdown();
    bool    isClose();
    string  toString();
    void    handleConnection();
    void    handleMessage();
    void    handleClose();

    void setCallback(TCPCallbcak &cb1,TCPCallbcak &cb2,TCPCallbcak &cb3){
        _onConnection = cb1;
        _onMessage = cb2;
        _onClose = cb3;
    }

private:
    InetAddress getLocalAddress();
    InetAddress getPeerAddress();
private:
    Socket          _socket;
    InetAddress     _localAddr;
    InetAddress     _peerAddr;
    EventLoop*      _loop;
    SocketIO        _sockIO;
    bool            _isShutdownWrite;

    TCPCallbcak     _onConnection;
    TCPCallbcak     _onMessage;
    TCPCallbcak     _onClose;

};

}//end of namespace

#endif


